package com.tgy.serialize;

import com.sun.xml.internal.messaging.saaj.util.ByteInputStream;

import java.io.*;

/**
 * @Author: tgy
 * @Date: 12/8/20 2:54 PM
 */
public class JDKSerialize<T> implements ISerialize<T> {
    @Override
    public byte[] serialize(T t) {

        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

        try {
            ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
            objectOutputStream.writeObject(t);
            return byteArrayOutputStream.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }

    @Override
    public T deserialize(byte[] data, Class<T> clazz) {

        ByteInputStream byteInputStream = new ByteInputStream(data,0,data.length);

        try {
            ObjectInputStream objectInputStream = new ObjectInputStream(byteInputStream);

            T t = (T)objectInputStream.readObject();

            return t;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }
}
